package com.itheima.category.controller;

import com.itheima.category.dao.CategoryMapper;
import com.itheima.category.service.CategoryService;
import com.itheima.goods.pojo.Category;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
//@CrossOrigin
public class CategoryController {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryService categoryService;

    //查询所有的分类
    @GetMapping("")
    public Result<List<Category>> findCategoryList(){
        List<Category> list = categoryMapper.selectList(null);
        return new Result<>(true, StatusCode.OK,"查询成功",list) ;
    }

    //添加分类
    @PostMapping("")
    public Result<Integer> addCategory(@RequestBody Category category){
        int insert = categoryMapper.insert(category);
        return new Result<>(true, StatusCode.OK,"添加成功",insert) ;
    }

    //通过分页获取分页数据
    @GetMapping("/search/{page}/{size}")
    public Result findCategoryListByPage(@PathVariable("page")Long page,
                                         @PathVariable("size")Long size){
        return categoryService.findCategoryListByPage(page,size);
    }

    //通过分页+查询过滤 获取分页数据
    @PostMapping("/search/{page}/{size}")
    public Result findCategoryListByPageAndSearch(@PathVariable("page")Long page,
                                                  @PathVariable("size")Long size,
                                                  @RequestBody  Category category){
        return categoryService.findCategoryListByPageAndSearch(page,size,category);
    }

    @GetMapping("/{id}")
    public Result findCategoryById(@PathVariable("id")Long id){
        Category category = null;
        if(id!= null){
            category = categoryMapper.selectById(id);
            return new Result<>(true, StatusCode.OK,"查询成功",category) ;
        }
        return new Result<>(true, StatusCode.ERROR,"查询失败",null) ;
    }

    @PutMapping("/{id}")
    public Result updateCategoryById(@PathVariable("id")Long id,
                                     @RequestBody Category category){
        return categoryService.updateCategoryById(id,category);
    }

    @DeleteMapping("/{id}")
    public Result deleteCategoryById(@PathVariable("id")Long id){
        int i = 0;
        if(id!= null){
            i = categoryMapper.deleteById(id);
            return new Result<>(true, StatusCode.OK,"删除成功",i);
        }
        return new Result<>(true, StatusCode.ERROR,"删除失败",i) ;
    }

}
